const momentService = require('../service/moment.service');

class MomentController {
  async create(ctx, next) {
    const { content } = ctx.request.body;
    const result = await momentService.create({ content, userId: ctx.user.id });
    ctx.body = { errorCode: 0, data: result };
  }

  async list(ctx, next) {
    const { pageSize = 10, pageNumber = 1 } = ctx.request.query;
    const result = await momentService.list({ pageSize, pageNumber });
    ctx.body = { errorCode: 0, data: result };
  }

  async detail(ctx, next) {
    const id = ctx.request.params.id;
    const result = await momentService.queryDetailById(id);
    ctx.body = { errorCode: 0, data: result };
  }
  async update(ctx, next) {
    const { id } = ctx.request.params;
    const { content } = ctx.request.body;
    const result = await momentService.updateContentById(id, content);
    if (result.affectedRows) {
      ctx.body = { errorCode: 0, data: '更新成功' };
    } else {
      ctx.body = { errorCode: -1, data: '更新失败' };
    }
  }
  async remove(ctx) {
    const result = await momentService.removeById(ctx.user.id, ctx.params.id);
    if (result.affectedRows) {
      ctx.body = { errorCode: 0, data: '删除成功' };
    } else {
      ctx.body = { errorCode: -1, data: '删除失败' };
    }
  }

  async addTags(ctx) {
    try {
      const { id, tags } = ctx.request.body;
      const result = await momentService.addTag(id, tags.split(','));
      ctx.body = { errorCode: 0, data: result };
    } catch (error) {
      ctx.body = { errorCode: -1, data: ErrorEvent.message };
    }
  }
}

module.exports = new MomentController();
